var theme = {
    // 默认色板
    color: [
        '#1790cf', '#1bb2d8', '#99d2dd', '#88b0bb',
        '#1c7099', '#038cc4', '#75abd0', '#afd6dd'
    ],

    // 图表标题
    title: {
        textStyle: {
            fontWeight: 'normal',
            color: '#1790cf'
        }
    },

    // 值域
    dataRange: {
        color: ['#1178ad', '#72bbd0']
    },

    // 工具箱
    toolbox: {
        color: ['#1790cf', '#1790cf', '#1790cf', '#1790cf']
    },

    // 提示框
    tooltip: {
        backgroundColor: 'rgba(0,0,0,0.5)',
        axisPointer: {            // 坐标轴指示器，坐标轴触发有效
            type: 'line',         // 默认为直线，可选为：'line' | 'shadow'
            lineStyle: {          // 直线指示器样式设置
                color: '#1790cf',
                type: 'dashed'
            },
            crossStyle: {
                color: '#1790cf'
            },
            shadowStyle: {                     // 阴影指示器样式设置
                color: 'rgba(200,200,200,0.3)'
            }
        }
    },

    // 区域缩放控制器
    dataZoom: {
        dataBackgroundColor: '#eee',            // 数据背景颜色
        fillerColor: 'rgba(144,197,237,0.2)',   // 填充颜色
        handleColor: '#1790cf'     // 手柄颜色
    },

    // 网格
    grid: {
        borderWidth: 0
    },

    // 类目轴
    categoryAxis: {
        axisLine: {            // 坐标轴线
            lineStyle: {       // 属性lineStyle控制线条样式
                color: '#1790cf'
            }
        },
        splitLine: {           // 分隔线
            lineStyle: {       // 属性lineStyle（详见lineStyle）控制线条样式
                color: ['#eee']
            }
        }
    },

    // 数值型坐标轴默认参数
    valueAxis: {
        axisLine: {            // 坐标轴线
            lineStyle: {       // 属性lineStyle控制线条样式
                color: '#1790cf'
            }
        },
        splitArea: {
            show: true,
            areaStyle: {
                color: ['rgba(250,250,250,0.1)', 'rgba(200,200,200,0.1)']
            }
        },
        splitLine: {           // 分隔线
            lineStyle: {       // 属性lineStyle（详见lineStyle）控制线条样式
                color: ['#eee']
            }
        }
    },

    timeline: {
        lineStyle: {
            color: '#1790cf'
        },
        controlStyle: {
            normal: {color: '#1790cf'},
            emphasis: {color: '#1790cf'}
        }
    },

    // K线图默认参数
    k: {
        itemStyle: {
            normal: {
                color: '#1bb2d8',          // 阳线填充颜色
                color0: '#99d2dd',      // 阴线填充颜色
                lineStyle: {
                    width: 1,
                    color: '#1c7099',   // 阳线边框颜色
                    color0: '#88b0bb'   // 阴线边框颜色
                }
            }
        }
    },

    map: {
        itemStyle: {
            normal: {
                areaStyle: {
                    color: '#ddd'
                },
                label: {
                    textStyle: {
                        color: '#c12e34'
                    }
                }
            },
            emphasis: {                 // 也是选中样式
                areaStyle: {
                    color: '#99d2dd'
                },
                label: {
                    textStyle: {
                        color: '#c12e34'
                    }
                }
            }
        }
    },

    force: {
        itemStyle: {
            normal: {
                linkStyle: {
                    color: '#1790cf'
                }
            }
        }
    },

    chord: {
        padding: 4,
        itemStyle: {
            normal: {
                borderWidth: 1,
                borderColor: 'rgba(128, 128, 128, 0.5)',
                chordStyle: {
                    lineStyle: {
                        color: 'rgba(128, 128, 128, 0.5)'
                    }
                }
            },
            emphasis: {
                borderWidth: 1,
                borderColor: 'rgba(128, 128, 128, 0.5)',
                chordStyle: {
                    lineStyle: {
                        color: 'rgba(128, 128, 128, 0.5)'
                    }
                }
            }
        }
    },

    gauge: {
        axisLine: {            // 坐标轴线
            show: true,        // 默认显示，属性show控制显示与否
            lineStyle: {       // 属性lineStyle控制线条样式
                color: [[0.2, '#1bb2d8'], [0.8, '#1790cf'], [1, '#1c7099']],
                width: 8
            }
        },
        axisTick: {            // 坐标轴小标记
            splitNumber: 10,   // 每份split细分多少段
            length: 12,        // 属性length控制线长
            lineStyle: {       // 属性lineStyle控制线条样式
                color: 'auto'
            }
        },
        axisLabel: {           // 坐标轴文本标签，详见axis.axisLabel
            textStyle: {       // 其余属性默认使用全局文本样式，详见TEXTSTYLE
                color: 'auto'
            }
        },
        splitLine: {           // 分隔线
            length: 18,         // 属性length控制线长
            lineStyle: {       // 属性lineStyle（详见lineStyle）控制线条样式
                color: 'auto'
            }
        },
        pointer: {
            length: '90%',
            color: 'auto'
        },
        title: {
            textStyle: {       // 其余属性默认使用全局文本样式，详见TEXTSTYLE
                color: '#333'
            }
        },
        detail: {
            textStyle: {       // 其余属性默认使用全局文本样式，详见TEXTSTYLE
                color: 'auto'
            }
        }
    },

    textStyle: {
        fontFamily: '微软雅黑, Arial, Verdana, sans-serif'
    }
}
var categoriesStatisticsOption = undefined;
var optionArr1 = new Array();
var optionArr2 = new Array();

window.onload = function () {
    layui.use(['form', 'layedit', 'laydate', 'laypage', 'table', 'laytpl', 'element'], function () {
        var form = layui.form
            , layer = layui.layer
            , layedit = layui.layedit
            , laydate = layui.laydate
            , laypage = layui.laypage
            , table = layui.table
            , element = layui.element;


        table.render({
            elem: '#company_active_rank'
            , url: contextPath + 'monitor/company_active_rank.sdo'
            , where: {pageNum: 1, pageSize: 5}
            , skin: 'line'
            , request: {
                pageName: 'pageNum' //页码的参数名称，默认：page
                , limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            , cols: [[
                {field: 'rank', width: 100,align:'center', title: '排名'}
                , {field: 'companyName', title: '企业名称'}
                , {field: 'readedCount', width: 100,align:'center', title: '阅读量'}
            ]]
            , page: false
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "status": res.status, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "total": res.data.total, //解析数据长度
                    "data": res.data.list //解析数据列表
                };
            }
            , response: {
                statusName: 'status' //规定数据状态的字段名称，默认：code
                , statusCode: 200 //规定成功的状态码，默认：0
                , countName: 'total' //规定数据总数的字段名称，默认：count
            }
            , done: function (res, curr, count) {
                // 回调
                $('.docs-wrapper .layui-table').addClass('sp_table');
            }
        });

        table.render({
            elem: '#policy_heat_rank'
            , url: contextPath + 'monitor/policy_heat_rank.sdo'
            , where: {pageNum: 1, pageSize: 5}
            , skin: 'line'
            , request: {
                pageName: 'pageNum' //页码的参数名称，默认：page
                , limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            , cols: [[
                {field: 'rank', width: 100,align:'center', title: '排名'}
                , {
                    field: 'title', title: '政策名', unresize: false,
                    templet: function (d) {
                        return "<a target='_blank' href='" + contextPath + "policy/detail.html?pkId=" + d.policyId + "'>" + d.policyTitle + "</a>";
                    }
                }
                , {field: 'readedCount', width: 100,align:'center', title: '阅读量'}
            ]]
            , page: false
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "status": res.status, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "total": res.data.total, //解析数据长度
                    "data": res.data.list //解析数据列表
                };
            }
            , response: {
                statusName: 'status' //规定数据状态的字段名称，默认：code
                , statusCode: 200 //规定成功的状态码，默认：0
                , countName: 'total' //规定数据总数的字段名称，默认：count
            }
            , done: function (res, curr, count) {
                // 回调
                $('.docs-wrapper .layui-table').addClass('sp_table');
            }
        });
        //style

        initIndustryStatistics();
        initTrendStatistics();
        initCategoryStatistics();

        //第二页
        initCategoriesStatistics();
        initIndustryProportion();
        initDepartmentProportion();

        //导航栏切换监听
        element.on('tab(nav_tab)', function (data) {
            if (data.index == 1) {
                var myChart = echarts.init(document.getElementById('industry_proportion_statistics'), theme);
                var myChart2 = echarts.init(document.getElementById('industry_2'), theme);
                var myChart3 = echarts.init(document.getElementById('industry_3'), theme);

                var myChart4 = echarts.init(document.getElementById('department_proportion_statistics'), theme);
                var myChart5 = echarts.init(document.getElementById('department_2'), theme);
                var myChart6 = echarts.init(document.getElementById('department_3'), theme);

                var categoryStatistics = echarts.init(document.getElementById('category_statistics'), theme);
                if (categoriesStatisticsOption) {
                    categoryStatistics.setOption(categoriesStatisticsOption);
                }
                if (optionArr1.length === 3) {
                    myChart.setOption(optionArr1[0]);
                    myChart2.setOption(optionArr1[1]);
                    myChart3.setOption(optionArr1[2]);
                }
                if (optionArr2.length === 3) {
                    myChart4.setOption(optionArr2[0]);
                    myChart5.setOption(optionArr2[1]);
                    myChart6.setOption(optionArr2[2]);
                }

            }else{
                initIndustryStatistics();
                initTrendStatistics();
                initCategoryStatistics();
            }
        });

        /*单选框*/
        form.on('radio(type1)', function (data) {
            var now = $(this).attr('data-id');
            $(this).closest('.layui-card-body').find(".js_cov").each(function (i, v) {
                var fal = $(this).attr('data-id');
                if (fal == now) {
                    $(this).show();
                    console.log(now, fal);
                } else {
                    $(this).hide();
                }
            })
        });

        form.on('radio(type2)', function (data) {
            var now = $(this).attr('data-id');
            $(this).closest('.layui-card-body').find(".js_cov").each(function (i, v) {
                var fal = $(this).attr('data-id');
                if (fal == now) {
                    $(this).show();
                    console.log(now, fal);
                } else {
                    $(this).hide();
                }
            })
        });
    })
}

function initIndustryStatistics() {
    $.ajax({
        url: contextPath + 'monitor/industry_readed_statistics.sdo',
        type: 'get',
        async: true,
        dateType: 'json',
        success: function (res) {
            var list = res.data;
            var names = new Array();
            var values = new Array();
            $.each(list, function (index, item) {
                names[index] = item.industryName;
                values[index] = item.readedCount;
            })

            var industryOption = {
                title: {
//		        text: '某地区蒸发量和降水量',
//		        subtext: '纯属虚构'
                },
//		    tooltip : {
//		        trigger: 'axis'
//		    },
//		    legend: {
//		        data:['蒸发量','降水量']
//		    },
                calculable: true,
                xAxis: [
                    {
                        type: 'category',
                        axisTick: {
                            alignWithLabel: true
                        },
                        axisLabel: {
                            interval: 0,
                            formatter: function (value) {
                                return formatX(value);
                            }
                        },
                        data: names
                    }
                ],
                yAxis: [
//		        {
//		            type : 'value'
//		        }
                ],
                series: [{
                    type: 'bar',
                    data: values,
                    markPoint: {
                        data: [
//		                    {name : '年最高', value :120, xAxis:5, yAxis: 120, symbolSize:15},
//		                    {name : '年最低', value : 2.3, xAxis: 0, yAxis: 3}
                        ]
                    },
                    markLine: {
                        data: [
                            {type: 'average', name: '平均值'}
                        ]
                    }
                }
                ]
            };
            var industryCharts = echarts.init(document.getElementById('policy_industry_statistics'),theme);
            if (industryOption) {
                industryCharts.setOption(industryOption);
            }
        },
        error: function (data) {
            console.error(data)
        }
    });
}

function initCategoryStatistics() {
    $.ajax({
        url: contextPath + 'monitor/policy_category_proportion.sdo',
        type: 'get',
        async: true,
        dateType: 'json',
        success: function (res) {
            var list = res.data;
            var datas = new Array();
            $.each(list, function (index, item) {
                var json = {};
                json.name = item.categoryName;
                json.value = item.percent;
                datas.push(json);
            })
            var categoryOption = {
                title: {
//		        text: '南丁格尔玫瑰图',
//		        subtext: '纯属虚构',
                    x: 'center'
                },
//		    tooltip : {
//		        trigger: 'item',
//		        formatter: "{a} <br/>{b} : {c} ({d}%)"
//		    },
//		    legend: {
//		        x : 'center',
//		        y : 'bottom',
//		        data:['rose1','rose2','rose3','rose4','rose5','rose6','rose7','rose8']
//		    },
//		    toolbox: {
//		        show : true,
//		        feature : {
//		            mark : {show: true},
//		            dataView : {show: true, readOnly: false},
//		            magicType : {
//		                show: true,
//		                type: ['pie', 'funnel']
//		            },
//		            restore : {show: true},
//		            saveAsImage : {show: true}
//		        }
//		    },
//		    calculable : true,
                series: [
                    {
                        name: '面积模式',
                        type: 'pie',
                        radius: '85%',
                        center: ['50%', 180],
                        roseType: 'area',
                        x: '50%',               // for funnel
                        max: 40,                // for funnel
                        sort: 'ascending',     // for funnel
                        data: datas
                    }
                ]
            };
            var categoryCharts = echarts.init(document.getElementById('policy_category_proportion'),theme);
            if (categoryOption) {
                categoryCharts.setOption(categoryOption);

            }
        },
        error: function (data) {
            console.error(data)
        }
    });
}

function initTrendStatistics() {
    $.ajax({
        url: contextPath + 'monitor/policy_readed_trend.sdo',
        type: 'get',
        async: true,
        dateType: 'json',
        success: function (res) {
            var list = res.data;
            var names = new Array();
            var values = new Array();
            $.each(list, function (index, item) {
                names[index] = item.month;
                values[index] = item.readedCount;
            })
            var trendOption = {
                title: {
//		        text: '某楼盘销售情况',
//		        subtext: '纯属虚构'
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['Web']
                },
                calculable: true,
                xAxis: [
                    {
                        type: 'category',
                        boundaryGap: false,
                        data: names
                    }
                ],
                yAxis: [
                    {
                        type: 'value'
                    }
                ],
                series: [
                    {
                        name: '阅读量',
                        type: 'line',
                        smooth: true,
                        itemStyle: {normal: {areaStyle: {type: 'default'}}},
                        data: values
                    }/*,
                    {
                        name: '短信',
                        type: 'line',
                        smooth: true,
                        itemStyle: {normal: {areaStyle: {type: 'default'}}},
                        data: [1320, 1132, 601, 234, 120, 90, 20]
                    }*/
                ]
            };
            var trendCharts = echarts.init(document.getElementById('policy_readed_trend'),theme);
            if (trendOption) {
                trendCharts.setOption(trendOption);
            }
        },
        error: function (data) {
            console.error(data)
        }
    });
}

function initCategoriesStatistics() {
    $.ajax({
        url: contextPath + 'monitor/category_statistics.sdo',
        type: 'get',
        async: true,
        dateType: 'json',
        success: function (res) {
            var list = res.data;
            var names = new Array();
            var policyArr = new Array();
            var interpretationArr = new Array();
            var pushArr = new Array();
            $.each(list, function (index, item) {
                names[index] = item.categoryName;
                policyArr[index] = item.policyTotal;
                interpretationArr[index] = item.interpretationTotal;
                pushArr[index] = item.pushTotal;
            })
            categoriesStatisticsOption = {
                title: {
//			        text: '某地区蒸发量和降水量',
//			        subtext: '纯属虚构'
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['政策数', '解读数', '推送数']
                },
                toolbox: {
                    show: false
                },
                calculable: true,
                xAxis: [
                    {
                        type: 'category',
                        data: names
                    }
                ],
                yAxis: [
                    {
                        type: 'value'
                    }
                ],
                series: [
                    {
                        name: '政策数',
                        type: 'bar',
                        data: policyArr,
                        markPoint: {
                            data: [
                                {type: 'max', name: '最大值'},
                                {type: 'min', name: '最小值'}
                            ]
                        },
                        markLine: {
                            data: [
                                {type: 'average', name: '平均值'}
                            ]
                        }
                    },
                    {
                        name: '解读数',
                        type: 'bar',
                        data: interpretationArr,
                        markPoint: {
                            data: [
                                {type: 'max', name: '最大值'},
                                {type: 'min', name: '最小值'}
                            ]
                        },
                        markLine: {
                            data: [
                                {type: 'average', name: '平均值'}
                            ]
                        }
                    },
                    {
                        name: '推送数',
                        type: 'bar',
                        data: pushArr,
                        markPoint: {
                            data: [
                                {type: 'max', name: '最大值'},
                                {type: 'min', name: '最小值'}
                            ]
                        },
                        markLine: {
                            data: [
                                {type: 'average', name: '平均值'}
                            ]
                        }
                    }
                ]
            };

        },
        error: function (data) {
            console.error(data)
        }
    });
}

function initIndustryProportion() {
    $.ajax({
        url: contextPath + 'monitor/industry_proportion_statistics.sdo',
        type: 'get',
        async: true,
        dateType: 'json',
        success: function (res) {
            var list = res.data;
            var values1 = new Array();
            var values2 = new Array();
            var values3 = new Array();
            $.each(list, function (index, item) {
                var json1 = {};
                json1.name = item.industryName;
                json1.value = item.policyPercent;
                values1.push(json1);

                var json2 = {};
                json2.name = item.industryName;
                json2.value = item.interpretationPercent;
                values2.push(json2);

                var json3 = {};
                json3.name = item.industryName;
                json3.value = item.pushPercent;
                values3.push(json3);
            })
            var option1 = {
                tooltip: {
                    trigger: 'item',
                    formatter: "{a} <br/>{b} : {c}% ({d}%)"
                },
//			    legend: {
//			        orient : 'vertical',
//			        x : 'left',
//			        data:['直达','营销广告','搜索引擎','邮件营销']
//			    },
                toolbox: {
                    show: false
                },
                calculable: false,
                series: [
                    {
                        name: '占比',
                        type: 'pie',
                        radius: [80, 120],
                        // for funnel
                        x: '60%',
                        width: '35%',
                        funnelAlign: 'left',
                        max: 1048,
                        data: values1
                    }
                ]
            };
            var option2 = {
                tooltip: {
                    trigger: 'item',
                    formatter: "{a} <br/>{b} : {c}% ({d}%)"
                },
//			    legend: {
//			        orient : 'vertical',
//			        x : 'left',
//			        data:['直达','营销广告','搜索引擎','邮件营销']
//			    },
                toolbox: {
                    show: false
                },
                calculable: false,
                series: [
                    {
                        name: '占比',
                        type: 'pie',
                        radius: [80, 120],
                        // for funnel
                        x: '60%',
                        width: '35%',
                        funnelAlign: 'left',
                        max: 1048,

                        data: values2
                    }
                ]
            };
            var option3 = {
                tooltip: {
                    trigger: 'item',
                    formatter: "{a} <br/>{b} : {c}% ({d}%)"
                },
//			    legend: {
//			        orient : 'vertical',
//			        x : 'left',
//			        data:['直达','营销广告','搜索引擎','邮件营销']
//			    },
                toolbox: {
                    show: false
                },
                calculable: false,
                series: [
                    {
                        name: '占比',
                        type: 'pie',
                        radius: [80, 120],
                        // for funnel
                        x: '60%',
                        width: '35%',
                        funnelAlign: 'left',
                        max: 1048,

                        data: values3
                    }
                ]
            };
            optionArr1[0] = option1;
            optionArr1[1] = option2;
            optionArr1[2] = option3;
        },
        error: function (data) {
            console.error(data)
        }
    });
}

function initDepartmentProportion() {
    $.ajax({
        url: contextPath + 'monitor/department_proportion_statistics.sdo',
        type: 'get',
        async: true,
        dateType: 'json',
        success: function (res) {
            var list = res.data;
            var values1 = new Array();
            var values2 = new Array();
            var values3 = new Array();
            $.each(list, function (index, item) {
                var json1 = {};
                json1.name = item.departmentName;
                json1.value = item.policyPercent;
                values1.push(json1);

                var json2 = {};
                json2.name = item.departmentName;
                json2.value = item.interpretationPercent;
                values2.push(json2);

                var json3 = {};
                json3.name = item.departmentName;
                json3.value = item.pushPercent;
                values3.push(json3);
            })
            var option1 = {
                tooltip: {
                    trigger: 'item',
                    formatter: "{a} <br/>{b} : {c}% ({d}%)"
                },
                toolbox: {
                    show: false
                },
                calculable: true,
                series: [
                    {
                        name: '占比',
                        type: 'pie',
                        radius: '70%',
                        center: ['50%', '50%'],
                        data:values1
                    }
                ]
            };

            var option2 = {
                tooltip: {
                    trigger: 'item',
                    formatter: "{a} <br/>{b} : {c}% ({d}%)"
                },
                toolbox: {
                    show: false
                },
                calculable: true,
                series: [
                    {
                        name: '占比',
                        type: 'pie',
                        radius: '70%',
                        center: ['50%', '50%'],
                        data: values2
                    }
                ]
            };
            var option3 = {
                tooltip: {
                    trigger: 'item',
                    formatter: "{a} <br/>{b} : {c}% ({d}%)"
                },
                toolbox: {
                    show: false
                },
                calculable: true,
                series: [
                    {
                        name: '占比',
                        type: 'pie',
                        radius: '70%',
                        center: ['50%', '50%'],
                        data: values3
                    }
                ]
            };
            optionArr2[0] = option1;
            optionArr2[1] = option2;
            optionArr2[2] = option3;
        },
        error: function (data) {
            console.error(data)
        }
    });
}

function formatX(params) {
    var newParamsName = "";// 最终拼接成的字符串
    var paramsNameNumber = params.length;// 实际标签的个数
    var provideNumber = 6;// 每行能显示的字的个数
    var rowNumber = Math.ceil(paramsNameNumber / provideNumber);// 换行的话，需要显示几行，向上取整
    /**
     * 判断标签的个数是否大于规定的个数， 如果大于，则进行换行处理 如果不大于，即等于或小于，就返回原标签
     */
    // 条件等同于rowNumber>1
    if (paramsNameNumber > provideNumber) {
        /** 循环每一行,p表示行 */
        for (var p = 0; p < rowNumber; p++) {
            var tempStr = "";// 表示每一次截取的字符串
            var start = p * provideNumber;// 开始截取的位置
            var end = start + provideNumber;// 结束截取的位置
            // 此处特殊处理最后一行的索引值
            if (p == rowNumber - 1) {
                // 最后一次不换行
                tempStr = params.substring(start, paramsNameNumber);
            } else {
                // 每一次拼接字符串并换行
                tempStr = params.substring(start, end) + "\n";
            }
            newParamsName += tempStr;// 最终拼成的字符串
        }

    } else {
        // 将旧标签的值赋给新标签
        newParamsName = params;
    }
    //将最终的字符串返回
    return newParamsName
}
